//==========================================================================
// Copyright (c) 2000-2008,  Elastos, Inc.  All Rights Reserved.
//==========================================================================

#include <stdlib.h>
#include <ctype.h>

long __cdecl atol(const char * nptr)
{
    int c;              /* current char */
    long total;         /* current total */
    int sign;           /* if '-', then negative, otherwise positive */

    if (!nptr) return 0;

    /* skip whitespace */
    while (isspace((int)(unsigned char)*nptr))
        ++nptr;

    c = (int)(unsigned char)*nptr++;
    sign = c;           /* save sign indication */
    if (c == '-' || c == '+')
        c = (int)(unsigned char)*nptr++;    /* skip sign */

    total = 0;

    while (isdigit(c)) {
        total = 10 * total + (c - '0');     /* accumulate digit */
        c = (int)(unsigned char)*nptr++;    /* get next char */
    }

    if (sign == '-')
        return -total;
    else
        return total;   /* return result, negated if necessary */
}

int __cdecl atoi(const char * string)
{
    int v = 0;
    int neg = 0;
    char c;

    if (!string) return 0;

    do {
        c = *string++;
    } while (isspace(c));

    if (c == '+') {
        c = *string++;
    }
    else if (c == '-') {
        neg = 1;
        c = *string++;
    }

    for (;;) {
        if (c < '0' || c > '9') {
            break;
        }
        v = (v * 10) + (int)(c - '0');
        c = *string++;
    }

    if (neg == 1) {
        v = 0 - v;
    }

    return v;
}

__int64 __cdecl _atoi64(const char *nptr)
{
    int c;              /* current char */
    __int64 total;        /* current total */
    int sign;           /* if '-', then negative, otherwise positive */

    if (!nptr) return 0;

    /* skip whitespace */
    while (isspace((int)(unsigned char)*nptr))
        ++nptr;

    c = (int)(unsigned char)*nptr++;
    sign = c;           /* save sign indication */
    if (c == '-' || c == '+')
        c = (int)(unsigned char)*nptr++;    /* skip sign */

    total = 0;

    while (isdigit(c)) {
        total = 10 * total + (c - '0');     /* accumulate digit */
        c = (int)(unsigned char)*nptr++;    /* get next char */
    }

    if (sign == '-')
        return -total;
    else
        return total;   /* return result, negated if necessary */
}
